<template>
  <!-- 表格上方固定区域 -->
  <div class="fixed-header">
    <el-row type="flex" align="middle" justify="space-between" style="padding: 10px;">
      <el-col :span="6">
        <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
      </el-col>
      <el-col :span="6" style="text-align: center;">
        <strong>总计：¥{{ totalPrice }}</strong>
      </el-col>
      <el-col :span="6" style="text-align: right;">
        <el-button type="primary" @click="checkout">去结算</el-button>
      </el-col>
    </el-row>
  </div>

  <!-- 购物车表格 -->
  <div class="cart-table-container">
    <el-table :data="cartItems" style="width: 100%" :row-style="{ height: '80px' }"
      :header-cell-style="{ background: '#f5f7fa' }">
      <!-- 复选框列 -->
      <el-table-column width="50">
        <template #default="scope">
          <el-checkbox v-model="scope.row.checked" :disabled="scope.row.goodsStatus === 0 || scope.row.goodsStock < 1"
            @change="() => handleCheckChange(scope.row)"></el-checkbox>
        </template>
      </el-table-column>

      <!-- 图片 -->
      <el-table-column label="图片" width="120">
        <template #default="scope">
          <div class="image-container">
            <img :src="scope.row.imageUrl" alt="商品图片" class="cart-img" />
          </div>
        </template>
      </el-table-column>

      <!-- 商品信息 -->
      <el-table-column label="商品信息">
        <template #default="scope">
          <div class="item-info">
            <strong>{{ scope.row.goodsName }}</strong><br />
            <span>{{ scope.row.goodsDesc }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 单价 -->
      <el-table-column label="单价" width="120">
        <template #default="scope"> ¥{{ scope.row.unitPrice }} </template>
      </el-table-column>

      <!-- 数量控制 -->
      <el-table-column label="数量" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity" :min="1" size="small"
            @change="handleQuantityChange(scope.row)"></el-input-number>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button size="small" type="danger" @click="removeCartItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from "../../api/axios.config";

export default {
  data() {
    return {
      cartItems: [],
      studentId: null, // 添加 studentId 变量
      totalPrice: 0, // 总价变量
      selectAll: false // 全选状态
    };
  },
  created() {
    this.fetchStudentId();
    this.fetchCartData().then(() => {
      this.calculateTotalPrice(); // 初始计算总价
    });
  },
  methods: {
    async initCartData() {  // 初始化购物车数据
      await this.fetchCartData();
      this.calculateTotalPrice();
    },
    fetchStudentId() {  // 获取用户学号
      const userData = localStorage.getItem('user');
      if (userData) {
        const parsedData = JSON.parse(userData);
        this.studentId = parsedData.studentId;
        console.log('Student ID:', this.studentId);
      } else {
        console.error('未找到用户信息');
      }
    },
    async fetchGoodsData(goodsId) {  // 获取商品数据
      try {
        const response = await axios.get(`goods/findbyid/${goodsId}`);
        return response.data.data;
      } catch (error) {
        console.error('Error fetching goods data:', error);
        return null;
      }
    },
    async fetchCartData() {   // 获取购物车数据
      try {
        if (!this.studentId) {
          console.error('未找到用户学号');
          return;
        }

        const response = await axios.get(`carts/findById/${this.studentId}`);

        const cartData = response.data.data;
        console.log('response data:', cartData);
        if (cartData && cartData.length > 0) {
          for (let item of cartData) {
            const goodsData = await this.fetchGoodsData(item.product_id);
            if (goodsData) {
              this.cartItems.push({
                checked: false, // 默认勾选
                imageUrl: goodsData.first_img_url,
                goodsName: goodsData.goods_name,
                goodsDesc: goodsData.goods_desc,
                goodsStatus: goodsData.goods_status,//商品状态，1为正常，0为下架
                goodsStock: goodsData.goods_stock,
                unitPrice: item.unit_price,
                totalPrice: item.money,
                quantity: item.quantity,
                productId: item.product_id, // 确保包含 productId
                previousQuantity: item.quantity // 初始化 previousQuantity
              });
            }
          }
        }
      } catch (error) {
        console.error('Error fetching cart data:', error);
      }
    },
    removeItem(index) {  // 删除购物车项
      this.cartItems.splice(index, 1);
    },
    async handleQuantityChange(item) {//处理购物车数量变化
      try {
        if (!this.studentId) {
          console.error('未找到用户学号');
          return;
        }

        const { productId, quantity } = item;

        if (quantity > item.previousQuantity) {
          // 数量增加，调用增加接口
          await this.incrementCartItem(productId);
        } else if (quantity < item.previousQuantity) {
          // 数量减少，调用减少接口
          await this.decrementCartItem(productId);
        }

        // 更新 item 的 previousQuantity 为当前 quantity
        item.previousQuantity = quantity;

        // ✅ 新增：重新计算总价
        this.calculateTotalPrice();
      } catch (error) {
        console.error('更新购物车数量失败:', error);
      }
    },
    async incrementCartItem(productId) { //购物车+1
      await axios.post('carts/add', {
        user_id: this.studentId,
        product_id: productId
      });
      console.log('购物车数量增加成功');
    },
    async decrementCartItem(productId) {  //购物车-1
      await axios.put('carts/decrease', {
        user_id: this.studentId,
        product_id: productId
      });
      console.log('购物车数量减少成功');

    },
    async removeCartItem(item) { //删除购物车
      try {
        if (!this.studentId) {
          console.error('未找到用户学号');
          return;
        }

        const { productId } = item;

        // 调用删除接口
        await axios.delete('carts/removeOne', {
          data: {
            user_id: this.studentId,
            product_id: productId
          }
        });

        // 从 cartItems 中移除该项
        this.cartItems = this.cartItems.filter(cartItem => cartItem.productId !== productId);

        console.log('购物车记录删除成功');
      } catch (error) {
        console.error('删除购物车记录失败:', error);
      }
    },
    calculateTotalPrice() {  //计算总价
      this.totalPrice = this.cartItems
        .filter(item => item.checked && item.goodsStatus !== 0 && item.goodsStock >= 1)
        .reduce((sum, item) => sum + item.unitPrice * item.quantity, 0);
    },
    handleCheckChange() {  //处理勾选状态
      this.calculateTotalPrice();
      this.updateSelectAllStatus();
    },
    updateSelectAllStatus() { //更新全选状态
      this.selectAll = this.cartItems.every(item => item.checked);
    },
    handleSelectAll(checked) { //处理全选状态
      this.cartItems.forEach(item => {
        if (item.goodsStatus !== 0 && item.goodsStock >= 1) {
          item.checked = checked;
        }
      });
      this.calculateTotalPrice();
    },
    async checkout() {
      const selectedItems = this.cartItems.filter(item => item.checked);
      if (selectedItems.length === 0) {
        this.$message.warning('请至少选择一件商品');
        return;
      }

      try {
        const orderIds = []; // 用于收集订单ID
        for (const item of selectedItems) {
          // 提交订单
          const response = await axios.post('orders/add/', {
            buyer_id: this.studentId,
            item_id: item.productId
          });
          const orderId = response.data.data.orders;
          if (orderId) {
            orderIds.push(orderId); // 收集订单ID
          }
          // 删除购物车中对应的商品
          await this.removeCartItem(item);
        }
        //  付款
        const payResponse = await axios.post('/orders/pay', {
          orderIds: orderIds,
          amount: this.totalPrice
        });

        const paymentUrl = payResponse.data.data.paymentUrl;

        if (paymentUrl) {
          window.location.href = paymentUrl; // 跳转到支付宝支付页面
        } else {
          this.$message.error('支付链接为空，请重试');
        }

        // this.$message.success(`已提交结算，总金额为 ¥${this.totalPrice}`);
        //  批量更新订单状态为 1（已付款，待发货）
        this.updataOrderStatus(orderIds);
      } catch (error) {
        console.error('提交订单或删除购物车记录失败:', error);
        this.$message.error('提交订单失败，请重试');
      }
    },

    async updataOrderStatus(orderIds) {
      for (const orderId of orderIds) {
        try {
          await axios.put(`/orders/updateorders?order_id=${orderId}&order_status=1`);
          console.log(`订单 ${orderId} 状态更新为 1`);
        } catch (err) {
          console.error(`更新订单 ${orderId} 状态失败`, err);
        }
      }
    }

  }
};
</script>

<style scoped>
/* === 关键修复 === */
:deep(.el-table__cell) {
  padding: 8px 0;
  /* 增加单元格内边距 */
}

.cart-table-container {
  width: 95%;
  max-width: 1200px;
  /* 可选：限制最大宽度 */
  margin: 0 auto;
  /* 居中对齐 */
  padding: 20px 0;
}

.image-container {
  position: relative;
  /* 建立定位上下文 */
  width: 120px;
  /* 固定宽度 */
  height: 120px;
  /* 固定高度 */
  margin: 0 auto;
  /* 居中显示 */
  display: flex;
  align-items: center;
  justify-content: center;

}

.cart-img {
  max-width: 100%;
  /* 自适应宽度 */
  max-height: 100%;
  /* 自适应高度 */
  object-fit: contain;
  /* 完整显示图片 */
  border-radius: 4px;
  background-color: #f5f5f5;
}

.item-info {
  padding: 0 10px;
  text-align: left;
}

.fixed-header {
  position: sticky;
  top: 0;
  z-index: 999;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>